package org.example.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.ymcc.domain.Login;
import org.example.ymcc.domain.Permission;
import org.example.ymcc.mapper.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询到对应的登录账号
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, username));
        if(login != null){
            List<Permission> permissions = loginMapper.selectPermissionByUserId(login.getId());
            List<SimpleGrantedAuthority> permissionsList = permissions.stream()
                    .map(permission -> new SimpleGrantedAuthority(permission.getSn()))
                    .collect(Collectors.toList());
            String password = login.getPassword();
            login.setPassword(null);
            return new User(JSON.toJSONString(login),password,permissionsList);
        }
        return null;
    }


}
